package com.hwadee.property.controller.parking;

import com.hwadee.property.pojo.Parking;
import com.hwadee.property.service.IParkingService;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/parking")
@Api(tags = "车位管理-ParkingController")
@CrossOrigin
public class ParkingController {

    @Autowired
    private IParkingService parkingService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/property/page")
    @ApiOperation(value = "【物业】分页查询车位", notes = "物业根据条件分页查询车位信息")
    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,

            @ApiParam(value = "当前页码", required = true, example = "1")
            @RequestParam(value = "current", defaultValue = "1") int current,

            @ApiParam(value = "每页大小", required = true, example = "10")
            @RequestParam(value = "size", defaultValue = "10") int size,

            @ApiParam(value = "车位位置", example = "A-101")
            @RequestParam(value = "location", required = false) String location,

            @ApiParam(value = "车位状态", example = "已占用")
            @RequestParam(value = "status", required = false) String status,

            @ApiParam(value = "创建时间", example = "2025-03-24 12:00:00")
            @RequestParam(value = "createTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date createTime,

            @ApiParam(value = "更新时间", example = "2025-03-25 15:30:00")
            @RequestParam(value = "updateTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date updateTime) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 返回查询结果
            return getPage(token, current, size, userService.getById(userId).getCommunityId(), location, status, createTime, updateTime);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询车位信息失败");
        }
    }

    /**
     * 分页查询车位列表
     */
    @GetMapping("/page")
    @ApiOperation(value = "【管理员】分页查询车位", notes = "根据条件分页查询车位信息")
    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,

            @ApiParam(value = "当前页码", required = true, example = "1")
            @RequestParam(value = "current", defaultValue = "1") int current,

            @ApiParam(value = "每页大小", required = true, example = "10")
            @RequestParam(value = "size", defaultValue = "10") int size,

            @ApiParam(value = "小区ID", example = "1001")
            @RequestParam(value = "communityId", required = false) Long communityId,

            @ApiParam(value = "车位位置", example = "A-101")
            @RequestParam(value = "location", required = false) String location,

            @ApiParam(value = "车位状态", example = "已占用")
            @RequestParam(value = "status", required = false) String status,

            @ApiParam(value = "创建时间", example = "2025-03-24 12:00:00")
            @RequestParam(value = "createTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date createTime,

            @ApiParam(value = "更新时间", example = "2025-03-25 15:30:00")
            @RequestParam(value = "updateTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date updateTime) {

        PageResult<Parking> pageResult = parkingService.getPage(current, size, communityId, location, status, createTime, updateTime);
        return AjaxResult.success(pageResult);
    }

    /**
     * 获取所有车位信息
     */
    @GetMapping
    @ApiOperation(value = "【管理员】查询所有车位", notes = "获取所有车位信息")
    public AjaxResult getAllParkings() {
        List<Parking> parkings = parkingService.list();
        return AjaxResult.success(parkings);
    }

    /**
     * 根据车位ID查询车位详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "【管理员】根据车位ID查询车位详情", notes = "根据车位ID获取车位详情")
    public AjaxResult getParkingById(
            @ApiParam(value = "车位ID", required = true, example = "1")
            @PathVariable Long id) {
        Parking parking = parkingService.getById(id);
        List<Parking> parkings = new ArrayList<>();
        parkings.add(parking);
        return parking != null ? AjaxResult.success(parkings) : AjaxResult.fail("未找到该车位");
    }

    @PostMapping("/property")
    @ApiOperation(value = "【物业】新增车位", notes = "新增一条车位记录")
    public AjaxResult addParking(
            @RequestHeader("Authorization") String token,

            @ApiParam(value = "车位位置", required = true, example = "A-101")
            @RequestParam String location,

            @ApiParam(value = "车位状态", required = true, example = "已占用")
            @RequestParam String status) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 调用新增函数
            return addParking(userService.getById(userId).getCommunityId(), location, status);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("新增车位失败");
        }
    }

    /**
     * 新增车位
     */
    @PostMapping("/{communityID}")
    @ApiOperation(value = "【管理员】新增车位", notes = "新增一条车位记录")
    public AjaxResult addParking(
            @ApiParam(value = "小区ID", required = true, example = "1001")
            @PathVariable Long communityID,

            @ApiParam(value = "车位位置", required = true, example = "A-101")
            @RequestParam String location,

            @ApiParam(value = "车位状态", required = true, example = "已占用")
            @RequestParam String status) {

        Parking parking = new Parking();
        parking.setCommunityId(communityID);
        parking.setLocation(location);
        parking.setStatus(status);

        boolean success = parkingService.save(parking);
        return success ? AjaxResult.success(parking) : AjaxResult.fail("新增车位失败，可能是数据格式错误或数据库异常");
    }

    @PutMapping("/property")
    @ApiOperation(value = "【物业】更新车位信息", notes = "根据车位ID更新车位信息")
    public AjaxResult updateParking(
            @RequestHeader("Authorization") String token,

            @ApiParam(value = "车位ID", required = true, example = "1")
            @RequestParam Long id,

            @ApiParam(value = "车位位置", example = "A-101")
            @RequestParam(required = false) String location,

            @ApiParam(value = "车位状态", example = "已占用")
            @RequestParam(required = false) String status) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 先查询数据库是否存在该车位
            List<Parking> parkingList = parkingService.listByCommunityId(userService.getById(userId).getCommunityId());
            boolean flag = false;
            for (Parking i : parkingList){
                if (i.getId().equals(id)){
                    flag = true;
                    break;
                }
            }
            if (!flag) return AjaxResult.fail("未找到该车位，无法更新");

            // 调用更新函数
            return updateParking(token, id, userService.getById(userId).getCommunityId(), location, status);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("更新车位失败");
        }
    }

    /**
     * 更新车位信息
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "【管理员】更新车位信息", notes = "根据车位ID更新车位信息")
    public AjaxResult updateParking(@RequestHeader("Authorization") String token,
            @ApiParam(value = "车位ID", required = true, example = "1")
            @PathVariable Long id,

            @ApiParam(value = "小区ID", example = "1001")
            @RequestParam(required = false) Long communityID,

            @ApiParam(value = "车位位置", example = "A-101")
            @RequestParam(required = false) String location,

            @ApiParam(value = "车位状态", example = "已占用")
            @RequestParam(required = false) String status) {

        // 先查询数据库是否存在该车位
        Parking existingParking = parkingService.getById(id);
        if (existingParking == null) {
            return AjaxResult.fail("更新失败，车位ID不存在");
        }

        // 仅更新提供的字段
        if (communityID != null) existingParking.setCommunityId(communityID);
        if (location != null) existingParking.setLocation(location);
        if (status != null) existingParking.setStatus(status);
        existingParking.setUpdateTime(DateUtil.dateToString(new Date()));

        boolean success = parkingService.updateById(existingParking);
        return success ? AjaxResult.success(existingParking) : AjaxResult.fail("更新车位失败，可能是数据库异常");
    }

    @DeleteMapping("/property")
    @ApiOperation(value = "【物业】删除车位", notes = "根据车位ID删除车位")
    public AjaxResult deleteParkingProperty(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "车位ID", required = true, example = "1")
            @RequestParam Long id) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 先查询数据库是否存在该车位
            List<Parking> parkingList = parkingService.listByCommunityId(userService.getById(userId).getCommunityId());
            boolean flag = false;
            for (Parking i : parkingList){
                if (i.getId().equals(id)){
                    flag = true;
                    break;
                }
            }
            if (!flag) return AjaxResult.fail("未找到该车位，无法删除");

            // 调用删除函数
            return deleteParking(token, id);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("删除车位失败");
        }
    }

    /**
     * 删除车位
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "【管理员】删除车位", notes = "根据车位ID删除车位")
    public AjaxResult deleteParking(@RequestHeader("Authorization") String token,
            @ApiParam(value = "车位ID", required = true, example = "1")
            @PathVariable Long id) {
        boolean success = parkingService.removeById(id);
        return success ? AjaxResult.success("删除成功") : AjaxResult.fail("删除失败");
    }
}
